"""主窗口模块"""
import os
import logging
from pathlib import Path
import sys
from PyQt6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QLabel, QFileDialog, QMessageBox,
    QSpinBox, QDoubleSpinBox, QProgressBar, QStackedWidget
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal
from src.video_processor import VideoProcessor, SceneInfo
from .views.video_import_view import VideoImportView
from .views.scene_detection_view import SceneDetectionView
from .views.storyboard_view import StoryboardView
from .views.export_view import ExportView

class VideoProcessThread(QThread):
    """视频处理线程"""
    progress_updated = pyqtSignal(int)
    scenes_detected = pyqtSignal(list)
    error_occurred = pyqtSignal(str)
    
    def __init__(self, video_path, threshold, min_scene_length):
        super().__init__()
        self.video_path = video_path
        self.threshold = threshold
        self.min_scene_length = min_scene_length
        self.processor = VideoProcessor()
        
    def run(self):
        """运行处理线程"""
        try:
            # 加载视频
            if not self.processor.load_video(self.video_path):
                self.error_occurred.emit("无法加载视频文件")
                return
                
            # 获取视频信息
            video_info = self.processor.get_video_info()
            total_frames = video_info["total_frames"]
            
            # 检测场景
            scenes = self.processor.detect_scenes(
                threshold=self.threshold,
                min_scene_length=self.min_scene_length,
                progress_callback=lambda p: self.progress_updated.emit(int(p * 100))
            )
            
            # 发送结果
            self.scenes_detected.emit(scenes)
            
        except Exception as e:
            self.error_occurred.emit(str(e))
        finally:
            self.processor.release()

class MainWindow(QMainWindow):
    """主窗口类"""
    def __init__(self):
        super().__init__()
        self.setWindowTitle("视频场景一键分镜与剪映草稿生成系统")
        self.setMinimumSize(1200, 800)
        self._init_ui()
        self._connect_signals()
        self.current_data = {}

    def _init_ui(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        self.stacked = QStackedWidget()
        layout.addWidget(self.stacked)
        # 各功能页面
        self.page_import = VideoImportView()
        self.page_detect = SceneDetectionView()
        self.page_story = StoryboardView()
        self.page_export = ExportView()
        self.stacked.addWidget(self.page_import)
        self.stacked.addWidget(self.page_detect)
        self.stacked.addWidget(self.page_story)
        self.stacked.addWidget(self.page_export)
        self.stacked.setCurrentIndex(0)

    def _connect_signals(self):
        # 视频导入完成 -> 下一步
        self.page_import.video_loaded.connect(self._to_detect)
        # 场景检测完成 -> 下一步
        self.page_detect.scenes_detected.connect(self._to_story)
        # 分镜预览完成 -> 下一步
        self.page_story.export_requested.connect(self._to_export)
        # 各页面"上一步"信号（需在各页面实现）
        if hasattr(self.page_detect, 'back_requested'):
            self.page_detect.back_requested.connect(lambda: self.stacked.setCurrentIndex(0))
        if hasattr(self.page_story, 'back_requested'):
            self.page_story.back_requested.connect(lambda: self.stacked.setCurrentIndex(1))
        if hasattr(self.page_export, 'back_requested'):
            self.page_export.back_requested.connect(lambda: self.stacked.setCurrentIndex(2))

    def _to_detect(self, video_path):
        self.current_data['video_path'] = video_path
        self.page_detect.set_video_path(video_path)
        self.stacked.setCurrentIndex(1)

    def _to_story(self, scenes):
        self.current_data['scenes'] = scenes
        self.page_story.set_scenes(scenes)
        self.stacked.setCurrentIndex(2)

    def _to_export(self, scenes):
        self.current_data['scenes'] = scenes
        self.page_export.set_scenes(scenes, self.current_data.get('video_path'))
        self.stacked.setCurrentIndex(3)

    def _on_error(self, error_msg):
        """处理错误"""
        QMessageBox.critical(self, "错误", error_msg)
        self.status_label.setText("处理出错")
        self.progress_bar.setVisible(False)
                
    def closeEvent(self, event):
        """关闭窗口事件"""
        if self.process_thread and self.process_thread.isRunning():
            self.process_thread.terminate()
            self.process_thread.wait()
        self.processor.release()
        event.accept()
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec()) 